package controller

import (
	"github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo/v4"
	"github.com/labstack/gommon/log"
	"law_case_api/dto"
	"law_case_api/models"
	"law_case_api/services"
	"law_case_api/utils"
	"net/http"
	"strconv"
	"time"
)

// @Summary 创建合同事项信息
// @Tags 合同管理
// @Accept plain
// @Produce plain
// @Param CreateContractEvent body dto.ContractEventReq true " "
// @Success 200 {object} models.BaseResult
// @Failure 400 {object} models.BaseResult
// @Router /wzj/contract/event/create [post]
func CreateContractEvent(c echo.Context) error {
	resp := models.BaseResult{
		Code: 200,
	}
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*models.JwtCustomClaims)
	userid, _ := strconv.Atoi(claims.UserId)
	if userid == 0 {
		resp.Code = 400
		resp.Message = "用户信息不存在，请重新登录"
		return c.JSON(http.StatusOK, resp)
	}
	contractEventReq := dto.ContractEventResp{}
	if err := c.Bind(&contractEventReq); err != nil {
		resp.Code = 400
		resp.Message = err.Error()
		return c.JSON(http.StatusBadRequest, resp)
	}
	wzjContractEvent := models.WzjContractEvent{}
	utils.MapTo(contractEventReq, &wzjContractEvent)
	wzjContractEvent.CreateUserId = int64(userid)
	wzjContractEvent.CreateDate = time.Now().Unix()

	contract := services.ContractService{}
	boolRes, err := contract.CreateContractEvent(wzjContractEvent)
	if err == nil && boolRes {
		resp.Message = "创建合同事项记录成功"
		return c.JSON(http.StatusOK, resp)
	}
	log.Error("创建合同事项记录失败：", err) //增加日志信息
	resp.Code = 400
	resp.Message = "创建合同事项记录失败"
	return c.JSON(http.StatusOK, resp)
}

// @Summary 获取合同事项信息列表
// @Tags 合同管理
// @Accept plain
// @Produce plain
// @Param contractId query string true "合同id"
// @Success 200 {object} models.BaseResult
// @Failure 400 {object} models.BaseResult
// @Router /wzj/contract/event/list [get]
func GetContractEventList(c echo.Context) error {
	resp := models.BaseResult{
		Code: 200,
	}
	contractId, _ := strconv.Atoi(c.QueryParam("contractId"))
	if contractId == 0 {
		resp.Code = 400
		resp.Message = "合同编号不能为空"
		return c.JSON(http.StatusOK, resp)
	}
	contract := services.ContractService{}

	contractEventList, _, err := contract.GetContractEventListByContractId(contractId, 0, 0)
	if err != nil {
		resp.Code = 400
		resp.Message = "根据合同编号获取合同事项记录列表失败"
		return c.JSON(http.StatusOK, resp)
	}
	//格式化
	contractEventResp := []dto.ContractEventResp{}
	_ = utils.MapTo(contractEventList, &contractEventResp)
	resp.Data = contractEventResp
	return c.JSON(http.StatusOK, resp)
}
